package snapex;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@AutoConfigureAfter(EncryptablePropertiesConfiguration.class)
@MapperScan(basePackages = "snapex.core.mapper", sqlSessionFactoryRef = "snapexSqlSessionFactory")
public class MybatisConfigurationSnapex {

	@Bean("snapexDataSourceTM")
	@Primary
	public DataSourceTransactionManager transactionManager(@Qualifier("snapexDataSource") DataSource snapexDataSource) {
		return new DataSourceTransactionManager(snapexDataSource);
	}
	
	@Bean("snapexJdbcTemplate")
	@Primary
	public JdbcTemplate jdbcTemplate(@Qualifier("snapexDataSource") DataSource snapexDataSource) {
		return new JdbcTemplate(snapexDataSource);
	}

	@Bean("snapexSqlSessionFactory")
	@Primary
	public SqlSessionFactory snapexSqlSessionFactory(@Qualifier("snapexDataSource") DataSource datasource) throws Exception {	
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();		
		bean.setDataSource(datasource);
		return bean.getObject();
	}

	@Bean("snapexSqlSessionTemplate")
	@Primary
	public SqlSessionTemplate snapexSqlSessionTemplate(@Qualifier("snapexSqlSessionFactory") SqlSessionFactory sessionfactory) {
		return new SqlSessionTemplate(sessionfactory);
	}
	
	@Value("${spring.datasource.snapex.driverClassName}")
	String driverClassName;	
	@Value("${spring.datasource.snapex.url}")
	String url;
	@Value("${spring.datasource.snapex.username}")
	String username;
	@Value("${spring.datasource.snapex.password}")
	String password;
	
	@Bean("snapexDataSource")
	@Primary
//	@ConfigurationProperties(prefix = "spring.datasource.snapex")
	public DataSource snapexDataSource() {		
		return DataSourceBuilder.create().driverClassName(driverClassName).username(username).password(password).url(url).build();
	}	
}